// 用户状态管理
const state = {
	token: uni.getStorageSync('token') || '',
	userInfo: uni.getStorageSync('userInfo') || null
}

const getters = {
	// 获取token
	token: state => state.token,
	// 获取用户信息
	userInfo: state => state.userInfo,
	// 判断是否登录
	isLogin: state => !!state.token
}

const mutations = {
	SET_TOKEN(state, token) {
		state.token = token
		uni.setStorageSync('token', token)
	},
	SET_USER_INFO(state, userInfo) {
		state.userInfo = userInfo
		uni.setStorageSync('userInfo', userInfo)
	},
	CLEAR_USER(state) {
		state.token = ''
		state.userInfo = null
		uni.removeStorageSync('token')
		uni.removeStorageSync('userInfo')
	}
}

const actions = {
	// 登录
	login({ commit }, userInfo) {
		return new Promise((resolve, reject) => {
			commit('SET_TOKEN', userInfo.token)
			commit('SET_USER_INFO', userInfo.userInfo)
			resolve()
		})
	},
	
	// 设置token
	setToken({ commit }, token) {
		commit('SET_TOKEN', token)
	},
	
	// 设置用户信息
	setUserInfo({ commit }, userInfo) {
		commit('SET_USER_INFO', userInfo)
	},
	
	// 登出
	logout({ commit }) {
		return new Promise((resolve, reject) => {
			commit('CLEAR_USER')
			resolve()
		})
	},
	
	// 获取用户信息
	getUserInfo({ commit }) {
		return new Promise((resolve, reject) => {
			// 这里不需要实际调用接口，因为接口调用已经在组件中完成
			resolve()
		})
	}
}

export default {
	state,
	getters,
	mutations,
	actions
} 